<!-- ERP 产品库存列表 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          clearable
          filterable
          placeholder="请选择仓库"
          class="!w-240px"
        >
          <el-option v-for="item in warehouse" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓位" prop="zoneId">
        <el-select
          v-model="queryParams.zoneId"
          clearable
          filterable
          placeholder="请选择仓位"
          class="!w-240px"
        >
          <el-option
            v-for="item in warehouseZone"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brandIds">
        <el-select
          v-model="queryParams.brandIds"
          clearable
          filterable
          multiple
          placeholder="请选择品牌"
          class="!w-240px"
        >
          <el-option
            v-for="item in productBrand"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          clearable
          filterable
          placeholder="请选择业务类型"
          class="!w-240px"
        >
          <el-option
            v-for="item in productCategory"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库存" prop="isNum">
        <el-radio-group v-model="queryParams.isNum">
          <el-radio :value="0" size="large">全部</el-radio>
          <el-radio :value="1" size="large">>0</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:stock:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:stock:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      show-summary
      :summary-method="getSummaries"
      @selection-change="handleSelectionChange"
      border
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column label="编号" prop="id" min-width="80px" max-width="260px">
        <!-- <template #default="scope">
          【{{scope.row.brandName}}】{{scope.row.productName}}-{{scope.row.businessTypeName}}
        </template> -->
      </el-table-column>
      <el-table-column label="产品名称" prop="productName" min-width="260px">
        <template #default="scope">
          【{{ scope.row.brandName }}】{{ scope.row.productName }}-{{ scope.row.businessTypeName }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="产品单位" align="center" prop="unitName" />-->
      <el-table-column label="产品分类" align="center" prop="categoryName" min-width="100px" />
      <!--  <el-table-column
        label="库存量"
        align="center"
        prop="count"
        :formatter="erpCountTableColumnFormatter"
      /> -->
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column
        label="总数"
        :formatter="erpCountTableColumnFormatter"
        align="center"
        prop="count"
      />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="库存上限" prop="upperLimit" align="center" min-width="100">
        <template #default="scope">
          <CustomInput :row="scope.row" :key-value="'upperLimit'" @success="getList" />
        </template>
      </el-table-column>
      <el-table-column label="库存下限" prop="lowerLimit" align="center" min-width="100">
        <template #default="scope">
          <CustomInput :row="scope.row" :key-value="'lowerLimit'" @success="getList" />
        </template>
      </el-table-column>
       <el-table-column label="是否预警" prop="limitStatus" align="center" min-width="100">
        <template #default="scope">
          <el-select :model-value="scope.row.limitStatus" @change="(value) =>handleStatechange(scope.row, value)" >
            <el-option
              label="关闭"
              :value="0"
            />
            <el-option
              label="开启"
              :value="1"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-popover
            placement="top"
            width="920"
            @before-leave="() => (formEngineerData = [])"
            @show="queryInfo('detail', scope.row)"
          >
            <template #reference>
              <el-button link v-hasPermi="['erp:stock-out:query']">详情 </el-button>
            </template>
            <el-table :data="formEngineerData" border class="-mt-10px">
              <el-table-column label="产品名称" prop="productName" align="center" min-width="150" />
              <el-table-column
                label="仓库名称"
                prop="warehouseName"
                align="center"
                min-width="150"
              />
              <el-table-column label="库位名称" prop="zoneName" align="center" min-width="150" />
              <el-table-column label="数量" prop="count" align="center" min-width="150" />
              <el-table-column label="单价" prop="price" align="center" min-width="150" />
              <el-table-column label="总价" prop="totalPrice" align="center" min-width="150" />
            </el-table>
          </el-popover>

          <el-button
            v-if="scope.row.count === 0"
            link
            @click="purchase(scope.row)"
            v-hasPermi="['erp:stock-out:query']"
            >采购
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!--库存详情 -->
  <!-- <el-dialog v-model="dialogProductVisible" title="库存详情信息" width="950">
    <el-table :data="formEngineerData" border class="-mt-10px">
      <el-table-column label="产品名称" prop="productName" align="center" min-width="150" />
      <el-table-column label="仓库名称" prop="warehouseName" align="center" min-width="150" />
      <el-table-column label="库位名称" prop="zoneName" align="center" min-width="150" />
      <el-table-column label="数量" prop="count" align="center" min-width="150" />
      <el-table-column label="单价" prop="price" align="center" min-width="150" />
      <el-table-column label="总价" prop="totalPrice" align="center" min-width="150" />
    </el-table>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogProductVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSyncProductInfo">确定</el-button>
      </div>
    </template>
  </el-dialog> -->
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { StockApi, StockVO } from '@/api/erp/stock/stock'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { erpCountTableColumnFormatter } from '@/utils'
import { useCommonOptions } from '@/hooks/web/useOption'
import { formatCusNumber } from '@/utils/formatter'
import CustomInput from './CustomInput.vue'

/** ERP 产品库存列表 */
defineOptions({ name: 'ErpStock' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<StockVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productName: undefined,
  warehouseId: undefined,
  zoneId: undefined,
  brandIds: [],
  businessType: undefined,
  isNum: 0,
  categoryId: undefined
})
const { productBrand, warehouseZone, businessType, warehouse, productCategory } = useCommonOptions()
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const summaryInfo = ref({
  count: 0,
  price: 0,
  totalPrice: 0
})
const selectionList = ref([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const query = { ...queryParams }
    query.brandIds = query.brandIds.join(',')
    const data = await StockApi.getStockPage(query)
    const { count, price, totalPrice, page } = data
    list.value = page.list
    total.value = count

    summaryInfo.value = {
      count,
      price,
      totalPrice
    }
  } finally {
    loading.value = false
  }
}
const getSummaries = (param) => {
  const { columns } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = Object.keys(summaryInfo.value)
    if (keys.includes(column.property)) {
      sums[index] = formatCusNumber(summaryInfo.value[column.property])
    } else {
      sums[index] = ''
    }
  })
  return sums
}
const handleSelectionChange = (rows) => {
  selectionList.value = rows
}
const handleStatechange = async (row, value) => {
  await StockApi.updateProduct({...row, limitStatus: value})
  message.success('修改预警成功')
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const dialogProductVisible = ref(false)
const formEngineerData = ref([])
/** 详情操作 */
const formRef = ref()
const queryInfo = async (type: string, row?: any) => {
  //formRef.value.open(type, id);
  //dialogProductVisible.value = true

  let queryParm = {
    pageNo: 1,
    pageSize: 100,
    productId: row.productId,
    warehouseId: row.warehouseId
  }
  const res = await StockApi.getStockPage(queryParm)
  formEngineerData.value = res.page.list
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StockApi.deleteStock(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StockApi.exportStock(queryParams)
    download.excel(data, '产品库存.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const purchase = async (data) => {
  await StockApi.createOrderByProductId(data.productId)
  message.success('采购成功')
  await getList()
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表
  // productList.value = await ProductApi.getProductSimpleList()

  productList.value = await ProductApi.getProductSimpleList()
  for (let i = 0; i < productList.value.length; i++) {
    productList.value[i].name =
      '【' +
      productList.value[i].brandName +
      '】' +
      productList.value[i].name +
      productList.value[i].businessTypeName
  }

  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
})
</script>
